package com.demo.connectdbtest.report;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPRow;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class ReportBalanceController {

    public static void main(String[] args) throws DocumentException {
        ArrayList<ContentItem> contentItems = new ArrayList<>();
        ContentItem contentItem = new ContentItem();
        contentItem.setPickupDate("ZN035233-ZN035233");
        contentItem.setProductSpecs("PCVPCVPCVSPBC");
        contentItem.setWeight("100020003000");
        contentItem.setTaxedStatementsPrice("22");
        contentItem.setSumTaxedStatementsPrice("3000");
        contentItem.setTwo("2000-2000-你好");
        contentItem.setThree("3000");
        contentItem.setFour("4000");
        contentItems.add(contentItem);
        contentItems.add(contentItem);
        contentItems.add(contentItem);
        contentItems.add(contentItem);
        contentItems.add(contentItem);

        JSONObject data = new JSONObject();
        data.put("centerStatementsItemVOS", contentItems);
        data.put("totalScore", 1895);
        data.put("totalAmount", 998);

        //设置表头
        List<String> headList = new ArrayList<>();
        headList.add("设备编号");
        headList.add("兑换类型(PCV/SBPC)");
        headList.add("兑换类型(PCV/SBPC)");
        headList.add("兑换数量");


        //表格中每一列的属性名
        List<String> contentList = new ArrayList<>();
        contentList.add("pickupDate");
        contentList.add("productSpecs");
        contentList.add("weight");
        contentList.add("taxedStatementsPrice");


        //指定列宽度
        ArrayList<Integer> columnWidthList = new ArrayList<>();

        columnWidthList.add(50);
        columnWidthList.add(50);
        columnWidthList.add(50);
        columnWidthList.add(30);

        generatePdf("C:\\Users\\braver\\Desktop\\draft", "C:\\Users\\braver\\Desktop\\draft\\test10.pdf",
                "测试excel类型的pdf", "", data, headList, contentList, columnWidthList, PageSize.A2, 8);
    }

    /**
     * 生成结算单pdf
     *
     * @param folderName      生成文件的文件夹名称
     * @param fileName        生成文件的全路径文件名
     * @param titleName       文件内容标题
     * @param contentName     文件内容 传递一个JSONObeject对象,将导出的集合list数据放入key=centerStatementsItemVOS的value中
     * @param data            文件表格数据
     * @param headList        表头，每一列的表头名称
     * @param columnWidthList 表头的每一列宽度，如果不指定则根据表头的列数平均计算每一列的宽度
     * @param pageLayout      页面纸张的布局大小，为null则默认A4
     * @param fontSize        页面字体大小，为null则默认10
     * @return
     */
    public static File generatePdf(String folderName, String fileName, String titleName, String contentName, JSONObject data, List<String> headList, List<String> contentList, List<Integer> columnWidthList, Rectangle pageLayout, Integer fontSize) throws DocumentException {
        try {
            //页面大小
            Rectangle layout = PageSize.A4;
            if (Objects.nonNull(pageLayout)) {
                layout = pageLayout;
            }
            Rectangle rect = new Rectangle(layout);
            //创建文档对象
//            Document document = new Document(rect, 60, 60, 30, 30);
            Document document = new Document(rect, 8, 8, 30, 30);
            File folderFile = new File(folderName);
            if (!folderFile.exists()) {
                log.info("准备创建文件夹. ");
                folderFile.mkdirs();// 如果不存在，创建目录
                log.info("成功创建文件夹. ");
            }
            //设置输出流
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            // 本地调试用这个字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            Font fontTitle = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK);
            //字体
//            Font fontContent = new Font(bfChinese, 10, Font.NORMAL, BaseColor.BLACK);
            Integer size = 10;
            if (Objects.nonNull(fontSize) && fontSize > 0) {
                size = fontSize;
            }
            Font fontContent = new Font(bfChinese, size, Font.NORMAL, BaseColor.BLACK);

            Paragraph title = new Paragraph(titleName, fontTitle);
            //居中
            title.setAlignment(1);
            document.add(title);

            // 空一行
            Paragraph emptyRow = new Paragraph(10f, " ", fontContent);
            document.add(emptyRow);

            Paragraph content = new Paragraph(contentName, fontContent);
            document.add(content);

            // 空一行
            document.add(emptyRow);

//           int columnNum = 5;
            int columnNum = headList.size();
            PdfPTable headerTable = new PdfPTable(columnNum);
            headerTable.setWidthPercentage(100);
            if (CollectionUtils.isEmpty(columnWidthList)) {
                //没有指定每一列的宽度则平均分配宽度
                Integer columnWidth = 100 / columnNum;
                List<Integer> headerWidthList = new ArrayList<>();
                for (int i = 0; i < columnNum; i++) {
                    headerWidthList.add(columnWidth);
                }
                int[] headerwidths = headerWidthList.stream().mapToInt(Integer::intValue).toArray();
                headerTable.setWidths(headerwidths);
            } else {
                int[] headerwidths = columnWidthList.stream().mapToInt(Integer::intValue).toArray();
                headerTable.setWidths(headerwidths);
            }


            for (int i = 0; i < headList.size(); i++) {
                createTableCell(headList.get(i), fontContent, headerTable, null, null);
            }

            JSONArray centerStatementsItemVOS = data.getJSONArray("centerStatementsItemVOS");


            // 外层循环构建行，内层循环构建列
//            for (int i = 0; i < centerStatementsItemVOS.size(); i++) {
//                System.out.println("外层循环");
//                System.out.println(centerStatementsItemVOS.getJSONObject(i));
//                for (int j = 0; j < contentList.size(); j++) {
//                    System.out.println("遍历表格的内容");
//                    System.out.println(centerStatementsItemVOS.getJSONObject(i).getString(contentList.get(j)));
//                    createTableCell(centerStatementsItemVOS.getJSONObject(i).getString(contentList.get(j)), fontContent, headerTable, 2,i);
//                }
//            }


            Cell cell = new Cell(2, 1).add(new com.itextpdf.layout.element.Paragraph("设备名称"));
            headerTable.addCell(String.valueOf(cell));

            cell = new Cell(2, 1).add(new com.itextpdf.layout.element.Paragraph("设备安装位置"));
            cell = formatCell(cell, 20);
            headerTable.addCell(String.valueOf(cell));

            cell = new Cell(2, 1).add(new com.itextpdf.layout.element.Paragraph("设备安装位置"));
            cell = formatCell(cell, 20);
            headerTable.addCell(String.valueOf(cell));


            //对应前面的3
            cell = new Cell(1, 1).add(new com.itextpdf.layout.element.Paragraph("筹码类型"));
            Font fontContent1 = new Font(bfChinese, size, Font.NORMAL, BaseColor.BLACK);

            Phrase phrase1 = new Phrase("子项1", fontContent1);
            phrase1.add(Chunk.NEWLINE);

//            com.itextpdf.layout.element.List list = new com.itextpdf.layout.element.List();
//            list.add("1");
//            list.add("2");
//
//            PdfPCell subpdfcell = new PdfPCell();
//            subpdfcell.setColspan(2);
//            subpdfcell.setRowspan(1);
//            headerTable.addCell(subpdfcell);
//            cell = new Cell(1, 1).add(new com.itextpdf.layout.element.Paragraph("兑换奖赏码数量"));
//            cell = formatCell(cell, 20);
//            headerTable.addCell(String.valueOf(cell));
//
//            cell = new Cell(1, 1).add(new com.itextpdf.layout.element.Paragraph("兑换积分"));
//            cell = formatCell(cell, 20);
//            headerTable.addCell(String.valueOf(cell));


            document.add(headerTable);
            // 文件末尾添加字段说明
            document.add(new Paragraph("合计:1500.00", fontContent));
            ArrayList<PdfPRow> rows = headerTable.getRows();
            for (PdfPRow row : rows) {
                PdfPCell[] cells = row.getCells();
            }

            document.close();
            File file = new File(fileName);
            return file;
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建表格单元格
     *
     * @param content     内容
     * @param fontContent 字体
     * @param headerTable 表格对象
     */
    private static void createTableCell(String content, Font fontContent, PdfPTable headerTable, Integer colspanNum, Integer index) {
        Phrase phrase = new Phrase(content, fontContent);
        phrase.add(Chunk.NEWLINE);
        PdfPCell pdfPCell = new PdfPCell(phrase);

//http://t.csdnimg.cn/4En34
        pdfPCell.setHorizontalAlignment(1);
        pdfPCell.setVerticalAlignment(1);
        pdfPCell.setNoWrap(false);

//            pdfPCell.setRowspan(3);
//            pdfPCell.setColspan(1);
        headerTable.addCell(pdfPCell);

//        PdfPCell cell = new PdfPCell();
//        cell.setRowspan(2);//纵向合并 2行
//        cell.setColspan(3);//横向合并 3行
    }

    public static Cell formatCell(Cell cell, float height) {
        cell.setTextAlignment(TextAlignment.CENTER);
        cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
        cell.setHeight(height);
        return cell;
    }

}
